from django.shortcuts import render
from rest_framework.generics import get_object_or_404

from snippets.models import Snippet, TBook, TBookManager
from snippets.permissions import IsOwnerOrReadOnly
from snippets.serializers import SnippetSerializer, UserSerializer, TBookSerializer, TBookManagerSerializer
from django.contrib.auth.models import User
from rest_framework import viewsets
from rest_framework import permissions
from rest_framework import renderers
from rest_framework.decorators import action
from rest_framework.response import Response

from snippets.viewset.custom import CreateRetrieveViewSet


class UserViewSet(viewsets.ReadOnlyModelViewSet):
    """
    这viewset自动提供“列表”和“检索”操作。
    """
    queryset = User.objects.all()
    serializer_class = UserSerializer


class SnippetViewSet(viewsets.ModelViewSet):
    """
    这ViewSet自动提供“list”、“create”、“retrieve”，'update'和'destroy'(也就是删除）操作。
    此外，我们还提供了一个额外的“高亮显示”动作。
    """
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer
    permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]

    ##原来对应的视图类=》SnippetHighlight
    @action(detail=True, renderer_classes=[renderers.StaticHTMLRenderer])
    def highlight(self, request, *args, **kwargs):
        snippet = self.get_object()
        self.get_object()
        return Response(snippet.highlighted)

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)


class TBookViewSet(viewsets.ModelViewSet):
    """
    这ViewSet自动提供“list”、“create”、“retrieve”，'update'和'destroy'(也就是删除）操作。
    """
    queryset = TBook.objects.all()
    serializer_class = TBookSerializer
    permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)


class TBookManagerViewSet(CreateRetrieveViewSet):
    """
       这ViewSet自动提供“list”、“create”、“retrieve”，'update'和'destroy'(也就是删除）操作。
       """
    queryset = TBookManager.objects.all()
    serializer_class = TBookManagerSerializer
    #permission_classes = [permissions.NOT]

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)
